#pragma once

#include<iostream>
#include<unistd.h>
#include<sys/epoll.h>
#include"Common.hpp"
#include"Log.hpp"

using namespace LogModule;

class Epoller
{
    public:
    Epoller():_epfd(-1)
    {
        _epfd=epoll_create(128);
        if(_epfd<0)
        {
            LOG(LogLevel::FATAL)<<"EPOLL_CREATE ERROR!!!!";
            exit(EPOLL_CREATE_ERR);
        }
        LOG(LogLevel::INFO)<<"CREATE EPOLL SUCCESS"<<_epfd;
    }
    void ModEventHelper(int sockfd,uint32_t events,int oper)
    {
        epoll_event ev;
        ev.events=events;
        ev.data.fd=sockfd;
        int n=epoll_ctl(_epfd,oper,sockfd,&ev);
        if(n<0)
        {
            LOG(LogLevel::ERROR)<<"EPOLL_CTL ERROR";
            return;
        }
        LOG(LogLevel::INFO)<<"EPOLL_CTL SUCCESS"<<_epfd;
    }
    void AddEvent(int sockfd,uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_ADD);
    }
    void DelEvent(int sockfd)
    {
        epoll_ctl(_epfd,EPOLL_CTL_DEL,sockfd,nullptr);
    }
    void Modevent(int sockfd,uint32_t events)
    {
        ModEventHelper(sockfd,events,EPOLL_CTL_ADD);
    }
    int WaitEvent(epoll_event revs[],int maxnum,int timeout)
    {
        int n=epoll_wait(_epfd,revs,maxnum,timeout);
        if(n<0)
        {
            LOG(LogLevel::ERROR)<<"EPOLL_WAIT ERROR";
        }
        else if(n==0)
        {
            LOG(LogLevel::WARNING)<<"EPOLL_WAIT TIMEOUT";
        }
        else
        {
            
        }
        return n;
    }
    ~Epoller()
    {
        if(_epfd>0)
        {
            close(_epfd);
        }
    }
    private:
    int _epfd;
};